//
//  OrderListViewController.m
//  DaJiang
//
//  Created by sally on 16/10/5.
//  Copyright © 2016年 jiniu. All rights reserved.
//

#import "HMSegmentedControl.h"
#import "OrderCell.h"
#import "OrderListViewController.h"
#import "OrderModel.h"

@interface OrderListViewController ()<OrderDetailVcDelegate>

@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (assign, nonatomic) enum OrderStatusType orderStatusType;
@property (strong, nonatomic) NSMutableArray *tableData;
@property (assign, nonatomic) NSInteger pager;

@end

@implementation OrderListViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  [self setNotification];
  [self initControl];
  [self initData];
  [self setRefresh];
}

-(void)viewDidAppear:(BOOL)animated{
  //从订单详情退到订单列表，导航栏强制变白
  [[CommonMethod sharedCommonMethod] setNavAndStatusBar:self.navigationController.navigationBar style:NavStyle_Normal];
}

- (void)dealloc {
  [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)setNotification {
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadRefreshData) name:NoticeRefreshOrderListVc object:nil];
}

#pragma mark 初始化控件
- (void)initControl {
  if (self.orderType == OrderType_OrderExpert) { //我约的专家
    self.title = @"我约的专家";
  } else { //约我的人
    self.title = @"约我的人";
  }

  [self setSegmCtrl];
}

#pragma mark 初始化数据
- (void)initData {
  self.tableData = [NSMutableArray array];
  self.orderStatusType = OrderStatusType_Ing;
}

- (void)setRefresh {
  __weak typeof(self) weakSelf = self;
  // 添加下拉刷新列表数据功能
  _tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:weakSelf refreshingAction:@selector(loadRefreshData)];

  // 添加上拉加载更多列表数据功能
  _tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:weakSelf refreshingAction:@selector(loadMoreData)];

  // 触发刷新
  [self loadRefreshData];
}

#pragma mark - 获取数据
- (void)loadRefreshData {
  _pager = 1;
  [self loadData];
}

- (void)loadMoreData {
  _pager = _pager + 1;
  [self loadData];
}

- (void)loadData {
  self.tableView.footer.hidden = NO;
  NSInteger cursor = _pager > 1 ? [[self.tableData lastObject] orderid] : GCursorInit;
  if (_pager == 1) {
    [[CommonMethod sharedCommonMethod] createProgressHUDInView:self.view withMessage:@""];
  }

  if (self.orderType == OrderType_OrderExpert) { //我约的专家
    [OrderModel queryMyOrderListWithCursor:cursor type:self.orderStatusType completion:^(NSMutableArray *orderList) {
      [self loadDataList:orderList];
    }];
  } else { //约我的人
    [OrderModel queryExpertOrderListWithCursor:cursor type:self.orderStatusType completion:^(NSMutableArray *orderList) {
      [self loadDataList:orderList];
    }];
  }
}

- (void)loadDataList:(NSMutableArray *)datalist {
  if (datalist) {
    // 下拉刷新数据
    if (_pager == 1) {
      [self.tableData removeAllObjects];
      [self.tableData addObjectsFromArray:datalist];
      [self.tableView reloadData];
      
      if (datalist.count < GListCount) {
        self.tableView.footer.hidden = YES;
      }
    }
    // 上拉加载更多
    else {
      [self.tableData addObjectsFromArray:datalist];
      [self.tableView reloadData];
      if (datalist.count < GListCount) {
        self.tableView.footer.hidden = YES;
      }
    }
    
  } else {
    NSError *error = [OrderModel getLastError];
    [[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
  }
  
  [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
  [self.tableView.header endRefreshing];
  [self.tableView.footer endRefreshing];
}

#pragma mark - TableView data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return self.tableData.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];

  if (self.orderType == OrderType_OrderExpert) { //我约的专家
    return cell.frame.size.height - GNormalViewHeight * 2;
  } else { //约我的人
    return cell.frame.size.height;
  }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  OrderCell *cell = (OrderCell *) [tableView dequeueReusableCellWithIdentifier:@"OrderCell"];
  if (!cell) {
    cell = [[[NSBundle mainBundle] loadNibNamed:@"OrderCell" owner:nil options:nil] lastObject];
  }

  if (self.orderType == OrderType_OrderExpert) { //我约的专家
    cell.orderCellType = OrderCellType_OrderExpert;
  } else { //约我的人
    cell.orderCellType = OrderCellType_OrderMe;
  }

  cell.cellData = [self.tableData objectAtIndex:indexPath.row];

  return cell;
}

#pragma mark TableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  [tableView deselectRowAtIndexPath:indexPath animated:YES]; //返回后选中状态消失
  
  OrderModel *orderModel = [self.tableData objectAtIndex:indexPath.row];
  OrderDetailType type;
  OrderNormalStatus normalStatus;
  OrderExpertStatus expertStatus;
  NSInteger status;
  if (self.orderType == OrderType_OrderMe) {//约我的人
    type = OrderDetailType_Expert;

    if ([orderModel.op_data.state_detail isEqualToString:@"admin_pass"]) {//后台审核通过
      expertStatus = OrderExpertStatus_ToBeConfirm;
    }else if ([orderModel.op_data.state_detail isEqualToString:@"confirmed"]){//专家确认可以见面
      expertStatus = OrderExpertStatus_ToMeet;
    }else if ([orderModel.op_data.state_detail isEqualToString:@"user_payed"]){//用户已支付
      expertStatus = OrderExpertStatus_ToMeet;
    }else if ([orderModel.op_data.state_detail isEqualToString:@"has_been_met"]){//专家已确认见面
      expertStatus = OrderExpertStatus_Finished;
    }else if ([orderModel.op_data.state_detail isEqualToString:@"commented"]){//用户已评价
      expertStatus = OrderExpertStatus_Finished;
    }else if ([orderModel.op_data.state_detail isEqualToString:@"cancelled"]){//用户取消见面
      expertStatus = OrderExpertStatus_Cancelled;
    }else if ([orderModel.op_data.state_detail isEqualToString:@"user_missed_meet"]){//用户没有来（失约）
      expertStatus = OrderExpertStatus_Cancelled;
    }else if ([orderModel.op_data.state_detail isEqualToString:@"pro_user_refused"]){//专家取消
      expertStatus = OrderExpertStatus_Cancelled;
    }

    status = expertStatus;
  }else{//我约的专家
    type = OrderDetailType_Normal;
    if ([orderModel.op_data.state_detail isEqualToString:@"book"]) {//用户预订
      normalStatus = OrderNormalStatus_ToBeConfirm;
    }else if ([orderModel.op_data.state_detail isEqualToString:@"admin_pass"]){//后台审核通过
      if (orderModel.op_data.remind_pro_user == 1) {//已提醒专家确认
        normalStatus = OrderNormalStatus_Reminded;
      }else{//未提醒过专家确认
        normalStatus = OrderNormalStatus_ToBeConfirm;
      }
    }else if ([orderModel.op_data.state_detail isEqualToString:@"admin_reject"]){//后台审核拒绝
      normalStatus = OrderNormalStatus_Cancelled;
    }else if ([orderModel.op_data.state_detail isEqualToString:@"confirmed"]){//专家确认可以见面
      normalStatus = OrderNormalStatus_ToPay;
    }else if ([orderModel.op_data.state_detail isEqualToString:@"user_payed"]){//用户已支付
      normalStatus = OrderNormalStatus_ToMeet;
    }else if ([orderModel.op_data.state_detail isEqualToString:@"has_been_met"]){//专家已确认见面
      normalStatus = OrderNormalStatus_Comment;
    }else if ([orderModel.op_data.state_detail isEqualToString:@"commented"]){//用户已评价
      normalStatus = OrderNormalStatus_Finished;
    }else if ([orderModel.op_data.state_detail isEqualToString:@"cancelled"]){//用户取消见面
      normalStatus = OrderNormalStatus_Cancelled;
    }else if ([orderModel.op_data.state_detail isEqualToString:@"user_missed_meet"]){//用户没有来（失约）
      normalStatus = OrderNormalStatus_NoMeet;
    }else if ([orderModel.op_data.state_detail isEqualToString:@"pro_user_refused"]){//专家取消
      normalStatus = OrderNormalStatus_Rejected;
    }

    status = normalStatus;
  }

  OrderDetailViewController *vc = [OperationManager gotoOrderDetailVcWithType:type status:status];
  vc.delegate = self;
  vc.orderModel = orderModel;
}

#pragma mark OrderDetailVcDelegate 刷新页面
- (void)refreshOrderListVc{
  [self loadRefreshData];
}

#pragma mark - 私有方法
#pragma mark 设置导航栏
- (void)setSegmCtrl {
  HMSegmentedControl *segmCtrl = [[HMSegmentedControl alloc] init];

  if (self.orderType == OrderType_OrderExpert) { //我约的专家
    segmCtrl.sectionTitles = @[ @"进行中", @"待评价", @"已结束" ];
    [OperationManager configSegment:segmCtrl type:SegmentedType_OrderExpert];
  } else { //约我的人
    segmCtrl.sectionTitles = @[ @"进行中", @"已结束" ];
    [OperationManager configSegment:segmCtrl type:SegmentedType_OrderMe];
  }

  [segmCtrl addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
  [self.headerView addSubview:segmCtrl];
  self.headerView.height = segmCtrl.height + 1;
}

#pragma mark 切换segment控件响应动作
- (void)segmentedControlChangedValue:(HMSegmentedControl *)segmentedControl {
  [self switchSegment:segmentedControl.selectedSegmentIndex];
}

- (void)switchSegment:(NSInteger)index {
  if (self.orderType == OrderType_OrderExpert) { //我约的专家
    self.orderStatusType = index;
  } else { //约我的人
    if (index == 0) {
      self.orderStatusType = OrderStatusType_Ing;
    } else {
      self.orderStatusType = OrderStatusType_End;
    }
  }
  // 刷新数据
  [self loadRefreshData];
}

@end
